package cn.hinglo.common.generator;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlReporter;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.hikaricp.HikariCpPlugin;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hinglo.common.generator.DatabaseToBeanGenerator.createDruidPlugin;

/**
 * @createTime: 2019/12/25 : 11:14
 * @author: HingLo
 * @description: 前端api 文件生成
 */
public class FrontApi {

    public static void main(String[] args) {
        PropKit.use("application.properties");
        HikariCpPlugin dataSourcePlugin = createDruidPlugin();
        dataSourcePlugin.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSourcePlugin.setMaximumPoolSize(2);
        //**** 数据操作插件****
        ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(dataSourcePlugin);
        // 设置方言
        activeRecordPlugin.setDialect(new MysqlDialect());
        //设置显示sql语句
        activeRecordPlugin.setShowSql(true);
        // 显示SQL的时候，使用日志输出的方式
        SqlReporter.setLog(true);
        dataSourcePlugin.start();
        activeRecordPlugin.start();
        List<Record> records = Db.find("select a.*,b.name as menuName from core_permission as a,core_menu as b WHERE mid=b.id order by mid,id asc");

        Engine engine = Engine.create("myEngine");
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.addSharedMethod(new StrKit());
        Template template = engine.getTemplate("cn/hinglo/common/generator/frontapi.jf");
        Map<String,Object> data=new HashMap<>(1);
        data.put("permissionList",records);
        String dataController = template.renderToString(data);
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\Project\\Maven\\PermissionAdmin\\front\\src\\common\\permission.js"), StandardCharsets.UTF_8)) {
            osw.write(dataController);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
